package com.unionwo.service;


import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.unionwo.commons.util.HttpUtils;
import com.unionwo.json.AddressComponent;
import com.unionwo.json.BaiduLocationInfoJson;
import com.unionwo.model.LocationResponse;
import com.unionwo.model.UnionResponse;

/****
 * 获取地理位置信息服务
 * @author admin
 *
 */
public class GetLocationService implements UnionService {

	private Logger log = Logger.getLogger(GetLocationService.class);
	@Override
	/*****
	 **@param x  经度
	 **@param y  纬度 
	 **@return UnionResponse
	 */
	public UnionResponse doRequest(HttpServletRequest request) throws Exception {
		double longitude = 0.0 ,latitude=0.0;
		try {
			longitude = Double.parseDouble(request.getParameter("x"));
			latitude = Double.parseDouble(request.getParameter("y"));
			log.info("longitude="+longitude+",latitude="+latitude);
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("longitude or latitude can not be convert to double.");
		}
		String url = "http://lbs.juhe.cn/api/getaddressbylngb?lngx="+longitude+"&lngy="+latitude;
		String json = HttpUtils.executeGet(url);
		log.info("Baidu Response json:"+json);
		LocationResponse res = new LocationResponse();
		
		JSONObject jsonObject = JSONObject.fromObject(json);
		
		BaiduLocationInfoJson bc = (BaiduLocationInfoJson)JSONObject.toBean(jsonObject, BaiduLocationInfoJson.class);
		if(bc==null){
			throw new Exception("the location get is null."+" longitude:"+longitude+";latitude"+latitude);
		}
		AddressComponent ac = null;
		try {
			ac = bc.getRow().getResult().getAddressComponent();
		} catch (NullPointerException e) {
			log.error("location convert error.");
		}
		if(null!=ac){
			res.setResult("ok");
			res.setP(ac.getProvince());
			res.setC(ac.getCity());
			res.setA(ac.getDistrict());
			res.setD(ac.getStreet()+ac.getStreet_number());
		}else{
			res.setResult("err");
		}
		return res;
	}

}
